import 'package:flutter/material.dart';

// 刷新演示
// 比较粗略，没有做互斥等
class RefreshDemo extends StatefulWidget {
  @override
  _RefreshDemoState createState() => _RefreshDemoState();
}

class _RefreshDemoState extends State<RefreshDemo> {
  final int pageSize = 30;
  final ScrollController _scrollController = ScrollController();
  // 包含[RefreshIndicator]的状态。此类可用于以编程方式显示刷新指示器，请参阅[show]方法。
  final GlobalKey<RefreshIndicatorState> refreshKey = GlobalKey();

  bool disposed = false;
  List<String> dataList = List();

  Future<void> onRefresh() async {
    await Future.delayed(Duration(seconds: 2));
    dataList.clear();
    for (int i = 0; i < pageSize; i++) {
      dataList.add('refresh');
    }
    if (disposed) {
      return;
    }
    setState(() {});
  }

  Future<void> loadMore() async {
    await Future.delayed(Duration(seconds: 2));
    for (int i = 0; i < pageSize; i++) {
      dataList.add("loadmore");
    }
    if (disposed) {
      return;
    }
    setState(() {});
  }

  @override
  initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        loadMore();
      }
      Future.delayed(Duration(seconds: 0), () {
        // 显示刷新
        refreshKey.currentState.show();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: new Text("RefreshDemoPage"),
      ),
      body: Container(
        child: RefreshIndicator(
          // GlobalKey，用户外部获取RefreshIndicator的State，做显示刷新
          key: refreshKey,
          // 下拉刷新触发，返回的是一个Future
          onRefresh: onRefresh,
          child: ListView.builder(
            // 保持ListView任何情况都能滚动，解决在RefreshIndicator的兼容问题。
            physics: const AlwaysScrollableScrollPhysics(),
            // 根据状态返回
            itemBuilder: (context, index) {
              if (index == dataList.length) {
                return Container(
                  margin: EdgeInsets.all(10),
                  child: Align(
                    child: CircularProgressIndicator(),
                  ),
                );
              }
              return Card(
                child: Container(
                  height: 60,
                  alignment: Alignment.centerLeft,
                  child: new Text("Item ${dataList[index]} $index"),
                ),
              );
            },
            // 根据状态返回数量
            itemCount: (dataList.length >= pageSize)
                ? dataList.length + 1
                : dataList.length,
            //滑动监听
            controller: _scrollController,
          ),
        ),
      ),
    );
  }
}
